<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Student Management</title>
    <link rel="stylesheet" href="/static/css/main.css">

<script src="/static/js/database.js"></script>
<script src="/static/js/config.js"></script>
    <script>
        function validateScore(input) {
            var value = parseFloat(input.value);
            if (isNaN(value) || value < 0 || value > 100 || (value * 2) % 1 !== 0) {
                alert('请输入0 - 100之间的有效数值，且只能以0.5为步长（如 85.5）');
                input.value = input.getAttribute('value') || '';
            } else {
                input.setAttribute('value', value);
            }
        }

        function loadContent(url) {
            fetch(url)
              .then(response => response.text())
              .then(data => {
                    document.getElementById('content').innerHTML = data;
                });
        }

        function showAddStudentForm() {
            // 创建一个模态框
            const modal = document.createElement('div');
            modal.style.position = 'fixed';
            modal.style.top = '0';
            modal.style.left = '0';
            modal.style.width = '100%';
            modal.style.height = '100%';
            modal.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
            modal.style.display = 'flex';
            modal.style.justifyContent = 'center';
            modal.style.alignItems = 'center';

            // 创建表单
            const form = document.createElement('form');
            form.style.backgroundColor = 'white';
            form.style.padding = '20px';
            form.style.borderRadius = '5px';
            form.style.boxShadow = '0 0 10px rgba(0, 0, 0, 0.3)';

            // 学号输入框
            const studentIdInput = document.createElement('input');
            studentIdInput.type = 'text';
            studentIdInput.placeholder = '学号';
            studentIdInput.required = true;
            form.appendChild(studentIdInput);

            // 姓名输入框
            const nameInput = document.createElement('input');
            nameInput.type = 'text';
            nameInput.placeholder = '姓名';
            nameInput.required = true;
            form.appendChild(nameInput);

            // 班级输入框
            const classInput = document.createElement('input');
            classInput.type = 'text';
            classInput.placeholder = '班级';
            classInput.required = true;
            form.appendChild(classInput);

            // 成绩输入框
            const scoreInput = document.createElement('input');
            scoreInput.type = 'number';
            scoreInput.placeholder = '成绩';
            scoreInput.step = '0.5';
            scoreInput.min = '0';
            scoreInput.max = '100';
            scoreInput.onblur = function() {
                validateScore(this);
            };
            form.appendChild(scoreInput);

            // 添加按钮
            const addButton = document.createElement('button');
            addButton.type = 'button';
            addButton.textContent = '添加';
            addButton.onclick = function() {
                const studentData = {
                    class: classInput.value,
                    name: nameInput.value,
                    studentId: studentIdInput.value,
                    score: parseFloat(scoreInput.value)
                };               
                // 已移除被注释的添加学生路由调用                

            };
            form.appendChild(addButton);

            // 关闭按钮
            const closeButton = document.createElement('button');
            closeButton.type = 'button';
            closeButton.textContent = '关闭';
            closeButton.onclick = function() {
                modal.remove();
            };
            form.appendChild(closeButton);

            // 将表单添加到模态框
            modal.appendChild(form);

            // 将模态框添加到页面
            document.body.appendChild(modal);
        }

        function showAllStudents() {
            fetch('{{ url_for('get_all_students') }}')
              .then(response => response.json())
              .then(data => {
                        const contentDiv = document.getElementById('content');
                        contentDiv.innerHTML = '';

                        const table = document.createElement('table');
                        table.className = 'data-table';
                        const thead = document.createElement('thead');
                        const headerRow = document.createElement('tr');
                        const headers = ['年级', '考试ID', '班级', '学号', '姓名', '生物成绩', '校排名', '班排名'];
                        headers.forEach(headerText => {
                            const th = document.createElement('th');
                            th.textContent = headerText;
                            headerRow.appendChild(th);
                        });
                        thead.appendChild(headerRow);
                        table.appendChild(thead);

                        const tbody = document.createElement('tbody');
                        data.forEach(student => {
                            const row = document.createElement('tr');
                            const { grade, exam_id, class_id, student_id, name, biology_score, school_rank, class_rank } = student;
                            const cells = [grade, exam_id, class_id, student_id, name, biology_score, school_rank, class_rank];
                            cells.forEach(cellText => {
                                const td = document.createElement('td');
                                td.textContent = cellText;
                                row.appendChild(td);
                            });
                            tbody.appendChild(row);
                        });
                        table.appendChild(tbody);

                        contentDiv.appendChild(table);
                    });
        }
        
        // 删除此处重复的handleImport函数定义
        // async function handleImport() {
        //     try {
        //         const fileInput = document.createElement('input');
        //         fileInput.type = 'file';
        //         fileInput.accept = '.csv, .xls, .xlsx';
        //         fileInput.addEventListener('change', async (event) => {
        //             const file = event.target.files[0];
        //             if (file) {
        //                 const formData = new FormData();
        //                 formData.append('file', file);
        //                 const response = await fetch('{{ url_for("import_scores") }}', { method: 'POST', body: formData });
        //                 const result = await response.json();
        //                 if (result.success) {
        //                     alert(result.message);
        //                     showAllScores(); // 刷新列表
        //                 } else {
        //                     alert(`导入失败: ${result.message}`);
        //                 }
        //             }
        //         });
        //         fileInput.click();
        //     } catch (error) {
        //         alert(`网络错误: ${error.message}`);
        //     }
        // }

        function showAllScores() {
            fetch('{{ url_for('get_all_scores') }}')
              .then(response => response.json())
              .then(data => {
                        const contentDiv = document.getElementById('content');
                        contentDiv.innerHTML = '';

                        contentDiv.innerHTML = `<table class='data-table'><thead><tr><th>年级</th><th>考试ID</th><th>班级</th><th>学号</th><th>姓名</th><th>生物成绩</th><th>校排名</th><th>班排名</th></tr></thead><tbody>${data.map(student => `<tr><td>${student.grade}</td><td>${student.exam_id}</td><td>${student.class_id}</td><td>${student.student_id}</td><td>${student.name}</td><td>${student.biology_score}</td><td>${student.school_rank}</td><td>${student.class_rank}</td></tr>`).join('')}</tbody></table>`;
                    });
        }

        document.addEventListener('DOMContentLoaded', function() {
            // 删除此处重复的清空数据库按钮事件绑定
            // document.getElementById('clear-db-btn').addEventListener('click', function(e) {
            //     e.preventDefault();
            //     if (confirm('确定要清空数据库吗？该操作不可恢复！')) {
            //         fetch('/clear_database', { method: 'POST' })
            //           .then(response => response.json())
            //           .then(data => {
            //                 if(data.success) {
            //                     alert('数据库已成功清空');
            //                     location.reload();
            //                 }
            //             });
            //     }
            // });
        });

// 统一事件绑定
document.addEventListener('DOMContentLoaded', function() {
    // 条件查询菜单事件
    document.getElementById('conditionalQueryMenu').addEventListener('click', function(e) {
        e.preventDefault();
        document.getElementById('queryForm').style.display = 'block';
        document.getElementById('database-status-table').style.display = 'none';
        document.getElementById('class-config').style.display = 'none';
        document.getElementById('content').innerHTML = '';
        loadQueryFilters();
    });

    document.querySelector('.import-link').addEventListener('click', handleImport);
    document.querySelector('.query-link').addEventListener('click', function() {
        document.getElementById('database-status-table').style.display = 'none';
        document.getElementById('class-config').style.display = 'none';
        document.getElementById('queryForm').style.display = 'none';
        showAllStudents();
    });
    document.querySelector('.status-link').addEventListener('click', function() {
        document.getElementById('database-status-table').style.display = 'block';
        document.getElementById('class-config').style.display = 'none';
        document.getElementById('queryForm').style.display = 'none';
        showDatabaseStatus();
    });
    document.querySelector('.config-link').addEventListener('click', function() {
        document.getElementById('database-status-table').style.display = 'none';
        document.getElementById('class-config').style.display = 'none';
        document.getElementById('queryForm').style.display = 'none';
        loadConfig();
    });

    // 新增班级配置按钮事件
    // 统一班级配置按钮事件绑定
    document.querySelectorAll('.class-config-link').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            document.getElementById('queryForm').style.display = 'none';
            document.getElementById('database-status-table').style.display = 'none';
            document.getElementById('class-config').style.display = 'block';
        });
    });
});

    </script>
</head>
<body>
    <div class="sidebar">
        <a href="#" class="import-link">导入成绩</a>
        <a href="#" class="query-link">查询所有</a>
        <a href='javascript:void(0);' class='status-link'>查询数据库状态</a>
        <a href="javascript:void(0);" class="config-link">查看配置</a>
        <a href='javascript:void(0);' class='button' onclick='loadBackups()'>备份数据库</a>        
        <a href="#" class="class-config-link" onclick="showClassConfig()">设置抽签班级</a>
        <a href="#" class="nav-link" id="conditionalQueryMenu"><i class="bi bi-search"></i> 条件查询</a>
        <a href="javascript:void(0);" class="button danger" id="clear-db-btn">清空数据库</a>
    </div>


    <div id="class-config" style="display:none; margin:20px;">
            <h3>选择抽签班级</h3>
            <div id="class-list"></div>
            <button onclick="saveChoosedClasses()" style="margin-top:10px;">保存配置</button>
        </div>
        <div class="content" id="content">
        <!-- 初始时内容为空 -->
        <!-- 删除此处多余的班级配置链接 -->
        </div>
    <div id="database-status-table" style="float: right; display: none;"></div>
</body>
</html>



<!-- 添加配置展示区域 -->
<!-- 备份数据库弹窗 -->
<div id="backup-modal" class="config-modal">
  <div class="config-content">
    <span class="close" onclick="document.getElementById('backup-modal').style.display='none'">&times;</span>
    <h3>可用备份</h3>
    <ul id="backup-list"></ul>
  </div>
</div>
<div id="config-modal" class="config-modal">
  <div class="config-content">
    <span class="close" onclick="closeConfig()">&times;</span>
    <pre id="config-data"></pre>
  </div>


</div>



<style>
.config-modal {
  display: none;
  position: fixed;
  right: 0;
  top: 0;
  width: 45%;
  height: 100%;
  background: rgba(0,0,0,0.5);
  z-index: 1000;
  padding: 20px;
}

.config-content {
  background: #f8f9fa;
  height: 90%;
  width: 100%;
  padding: 20px;
  border-radius: 8px 0 0 8px;
  box-shadow: -2px 0 8px rgba(0,0,0,0.1);
  overflow-y: auto;
}

#config-data {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  white-space: pre-wrap;
}

.json-key { color: #0366d6; }
.json-string { color: #22863a; }
.json-number { color: #b35900; }
.json-boolean { color: #6f42c1; }
.json-null { color: #d73a49; }
</style>

<script src="/static/js/database.js"></script>
<script src="/static/js/config.js"></script>

<script>
function loadConfig() {
  fetch('/config')
    .then(response => response.json())
    .then(data => {
      if(data.success) {
        const jsonString = JSON.stringify(data.config, null, 2);
        const highlighted = jsonString
          .replace(/"(\w+)":/g, '<span class="json-key">"$1":</span>')
          .replace(/: ("[^"]*")/g, ': <span class="json-string">$1</span>')
          .replace(/: (\d+\.?\d*)/g, ': <span class="json-number">$1</span>')
          .replace(/: (true|false)/g, ': <span class="json-boolean">$1</span>')
          .replace(/: null/g, ': <span class="json-null">null</span>');

        document.getElementById('config-data').innerHTML = highlighted;
        document.getElementById('config-modal').style.display = 'block';
      }
    });
}

function closeConfig() {
  document.getElementById('config-modal').style.display = 'none';
}
</script>



<div id="queryForm" style="display:none; padding:20px;">
    <div class="row g-3 mb-3">
        <div class="col-md-3">
            <select class="form-select" id="gradeSelect">
                <option value="">全部年级</option>
            </select>
        </div>
        <div class="col-md-3">
            <select class="form-select" id="examSelect">
                <option value="">全部考试</option>
            </select>
        </div>
        <div class="col-md-3">
            <select class="form-select" id="classSelect">
                <option value="">全部班级</option>
            </select>
        </div>
        <div class="col-md-3">
            <input type="text" class="form-control" id="nameInput" placeholder="学生姓名">
        </div>
    </div>
    <button class="btn btn-primary" id="searchButton">
        <i class="bi bi-search"></i> 查询
    </button>
    <div id="resultTable" class="mt-3"></div>
</div>